<?php

namespace Jinxing\Admin\Composers;

use Jinxing\Admin\Helpers\Storage;
use Illuminate\Contracts\View\View;
use Jinxing\Admin\Repositories\MenuRepository;

/**
 * 获取面包屑
 *
 * Class CategoryComposer
 * @package App\Composers
 */
class BreadCrumbsComposer
{
    /**
     * @var MenuRepository
     */
    private $menuRepository;

    public function __construct(MenuRepository $menuRepository)
    {
        $this->menuRepository = $menuRepository;
    }

    /**
     * Bind data to the view.
     *
     * @param View $view
     *
     * @return void
     * @throws \Exception
     */
    public function compose(View $view)
    {
        $data = Storage::get('bread-crumbs-composer');
        if (empty($data)) {
            // 获取菜单信息
            if (!$uris = Storage::get('uris')) {
                $uris = get_menu_uris();
                Storage::set('uris', $uris);
            }

            // 其他页面路由
            if ($active_menu = $view['__active_menu__'] ?? '') {
                $uris[] = '/' . trim($active_menu, '/');
            }

            // 获取到菜单ID
            $menu = [];
            foreach ($uris as $uri) {
                if ($menu = $this->menuRepository->find(['url' => $uri])) {
                    break;
                }
            }

            $breadCrumb     = [];
            $title          = $view['title'] ?? '';
            $description    = $view['description'] ?? '';
            $menu_id        = array_get($menu, 'id');
            $menu_parent_id = array_get($menu, 'parent') ?: $menu_id;
            if ($menu) {
                $title        = $title ?: $menu['name'];
                $breadCrumb[] = array_only($menu, ['id', 'name', 'url']);
                $parent_menu  = $menu;
                while ($id = array_get($parent_menu, 'parent')) {
                    if ($parent_menu = $this->menuRepository->find(['id' => $id])) {
                        array_unshift($breadCrumb, array_only($parent_menu, ['id', 'name', 'url']));
                        $description    = $description ?: $parent_menu['name'];
                        $menu_parent_id = array_get($parent_menu, 'id');
                    }
                }
            }

            // 设置到静态区中
            $data = compact('breadCrumb', 'title', 'description', 'menu_id', 'menu_parent_id');
            Storage::set('bread-crumbs-composer', $data);
        }

        $view->with($data);
    }
}